﻿using UnityEngine;
using System.Collections;

public class Enemy:MonoBehaviour {


    public float moveSpeed = 2f;

    public int HP = 2;

    public Sprite deadEnemy;

    public Sprite damagedEnemy;

    public AudioClip[] deathClips;

    public GameObject hunderdPointsUI;

    public float deathSpinMin = 100f;

    public float deathSpinMax = 100f;


    private SpriteRenderer ren;

    private Transform frontCheck;

    private bool dead = false;

    private Score score;


    private void Awake() {
        ren = transform.Find("body").GetComponent<SpriteRenderer>();
        frontCheck = transform.Find("frontCheck").transform;
        score = GameObject.Find("Text").GetComponent<Score>();
    }

    private void FixedUpdate() {

        // 在position 这个点上发射一个射线，返回所以被穿过的指定layerMask 的对象
        Collider2D[] frontHits = Physics2D.OverlapPointAll(frontCheck.position,1);
        foreach (Collider2D c in frontHits) {

                Filp();
          
        }

        GetComponent<Rigidbody2D>().velocity = new Vector2(transform.localScale.x * moveSpeed
            ,GetComponent<Rigidbody2D>().velocity.y);

        if (HP == 1 && damagedEnemy != null) {
            ren.sprite = damagedEnemy;
        }

        if (HP <= 0 && !dead) {

            Death();

        }

    }

    void Death() {
        //找到这个对象上的所有精灵渲染器，它的子对象。
        SpriteRenderer[] otherRenderers = GetComponentsInChildren<SpriteRenderer>();

        foreach (SpriteRenderer s in otherRenderers) {
            s.enabled = false;
        }

        // 重新启用主精灵渲染器，并将其精灵设置为死亡状态。
        ren.enabled = true;
        ren.sprite = deadEnemy;


        // 调用分数类记录分数
        score.scroe += 100;

        dead = true;

        //对刚体施加一个旋转力
        GetComponent<Rigidbody2D>().AddTorque(Random.Range(deathSpinMin,deathSpinMax));

        // 找到游戏对象上的所有对撞机，并将它们设置为触发器。
        Collider2D[] cols = GetComponents<Collider2D>();
        foreach (Collider2D c in cols) {
            c.isTrigger = true;
        }

        int i = Random.Range(0,deathClips.Length);
        AudioSource.PlayClipAtPoint(deathClips[i],transform.position);

        Vector3 scorePos;
        scorePos = transform.position;
        scorePos.y += 1.5f;

        Instantiate(hunderdPointsUI,scorePos,Quaternion.identity);
    }

    public void Hurt() {
        HP--;
    }

    public void Filp() {
        Vector3 enemyScale = transform.localScale;
        enemyScale.x *= -1;

        transform.localScale = enemyScale;
    }

}
